//创建仓库
const createStore = (reducer) => {
    // console.log(reducer)
    //状态
    let state;
    //监听函数数组
    let listeners = [];
    //getState用来获取最新的状态
    let getState = () => state;
    //向仓库派发action，
    let dispatch = (action) => {
        //传入老的state，action，经过reduce处理得到新的state
        state = reducer(state, action)
        //遍历执行监听的函数

        listeners.forEach(listener => listener())
    };
    //订阅仓库内的状态变化事件，当状态发生变化之后会调用对应的监听函数
    //订阅方法执行后会返回一个取消订阅的函数，调用它会取消订阅
    let subscribe = (listener) => {
        //订阅的时间
      /*  function() {
            this.setState({ number: store.getState().number });
        }*/
        listeners.push(listener)
        return () => {
            listeners.filter(l => listener !== l)
        }
    };
    dispatch();
    return {
        getState,//获取最新的状态对象
        subscribe, //原来订阅状态变化事件
        dispatch,  //派发事件
    }
};
//中间件
let applyMiddleware = middleware =>createStore => reducer => {
        let store = createStore(reducer);
        middleware = middleware(store)
        let dispatch = middleware(store.dispatch)
        return {...store, dispatch}
}
/*var applyMiddleware = function applyMiddleware(middleware) {
    return function (createStore) {
        return function (reducer) {
            var store = createStore(reducer);
            middleware = middleware(store);
            var dispatch = middleware(store.dispatch);
           return {...store, dispatch}
        };
    };
};*/
export {createStore, applyMiddleware}